package cn.bugDance.domain.activity.service.rule.impl;

import cn.bugDance.domain.activity.model.entity.ActivityCountEntity;
import cn.bugDance.domain.activity.model.entity.ActivityEntity;
import cn.bugDance.domain.activity.model.entity.ActivitySkuEntity;
import cn.bugDance.domain.activity.model.valobj.ActivitySkuStockSubtractionJobData;
import cn.bugDance.domain.activity.repository.IActivityRepository;
import cn.bugDance.domain.activity.service.rule.AbstractRuleChain;
import cn.bugDance.types.enums.ResponseCode;
import cn.bugDance.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component("ruleActivitySkuStockChain")
@Slf4j
public class RuleActivitySkuStockChain extends AbstractRuleChain {

    @Resource
    private IActivityRepository activityRepository;

    @Override
    public void action(ActivityEntity activityEntity, ActivitySkuEntity activitySkuEntity, ActivityCountEntity activityCountEntity) {

        Long sku = activitySkuEntity.getSku();
        Date endTime = activityEntity.getEndTime();

        boolean success = activityRepository.subtractionActivitySkuStock(sku, endTime);
        if(!success){
            log.info("【活动服务层-RuleActivitySkuStockChain】: 活动库存不足");
            throw new AppException(ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getCode(), ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getInfo());
        }

        ActivitySkuStockSubtractionJobData activitySkuStockSubtractionJobData = new ActivitySkuStockSubtractionJobData();
        activitySkuStockSubtractionJobData.setSku(sku);
        activityRepository.sendJobQueue(activitySkuStockSubtractionJobData);
    }
}
